import axios from 'axios'
import {Message} from 'element-ui'
import router from '../router'
import CookieUtil from '@/utils/cookies'

axios.defaults.timeout = 10000
axios.defaults.baseURL = process.env.VUE_APP_API_URL

let clientId = process.env.VUE_APP_CLIENT_ID

axios.interceptors.request.use(config => {
        let user = window.localStorage.getItem('manage_user')
        if (user) {
            user = JSON.parse(user)
            config.headers.Authorization = user.token
        }
        config.headers.ClientId = clientId
        return config
    }, err => {
        return Promise.reject(err)
    }
)

axios.interceptors.response.use(
    response => {
        if (response.data.code === '4000') {
            CookieUtil.removeLoginStatus()
            router.replace({path: '/login'})
            Message.error('登录信息失效，请重新登录')
            window.localStorage.removeItem('code_user')
        }

        if (response.data) {
            if (response.data instanceof Blob || response.data instanceof ArrayBuffer) {
                return response;
            }
        }

        return response.data
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    CookieUtil.removeLoginStatus()
                    router.replace({path: '/login'})
                    Message.error('登录信息失效，请重新登录')
                    window.localStorage.removeItem('code_user')
                    break
                case 404:
                    Message.error('请求的资源不存在')
                    break
                default:
                    Message.error('服务器异常')
                    break
            }
        } else {
            Message.error('网络异常')
        }
        return Promise.reject(error)
    })

export default axios
